#-*- coding: utf-8 -*-
import os
import sys
import zipfile
import urllib2
import warnings
import tempfile
import traceback

from selenose import consts

# Download URL for the server
SERVER_URL = 'http://selenium.googlecode.com/files/selenium-server-standalone-2.0a7.jar'

# Download URL for the grid
GRID_URL = 'http://release.seleniumhq.org/selenium-grid/selenium-grid-1.0.8-bin.zip'

# Current folder
FOLDER = os.path.dirname(os.path.abspath(__file__))

def download():
    '''
    Download required jars.
    '''
    try:
        download_server()
        download_grid()
    except Exception, e:
        traceback.print_exc()
        print >> sys.stderr, '''
===============================================================================
* Failed to download selenium jars. Try to download them manually from:
    - selenium server: %s
    - selenium grid: %s (jars are inside the zip file, in lib folder)
* Then put following files in %s and restart setup.py:
    - %s
    - %s
    - %s
===============================================================================
''' % (SERVER_URL, GRID_URL, FOLDER, consts.LIB_SERVER[1], consts.LIB_GRID_RC[1], consts.LIB_GRID_HUB[1])
        raise e

def download_server():
    '''
    Download server jar if not there.
    '''
    bn = os.path.basename(SERVER_URL)
    assert bn == consts.LIB_SERVER[1]
    fp = os.path.join(FOLDER, bn)
    if not os.path.exists(fp):
        print >> sys.stdout, 'Downloading %s' % SERVER_URL
        fd = open(fp, 'wb')
        try:
            fd.write(urllib2.urlopen(SERVER_URL).read())
        except Exception, e:
            fd.close()
            os.remove(fp)
            raise e
        fd.close()

def download_grid():
    '''
    Download grid jars if not there.
    '''
    there = True
    jfns = [ consts.LIB_GRID_HUB[1], consts.LIB_GRID_RC[1], ]
    for jfn in jfns:
        if not os.path.exists(os.path.join(FOLDER, jfn)):
            there = False
    if not there:
        print >> sys.stdout, 'Downloading %s' % GRID_URL
        fdint, fp = tempfile.mkstemp(suffix='.zip')
        fd = os.fdopen(fdint, 'wb')
        try:
            fd.write(urllib2.urlopen(GRID_URL).read())
        except Exception, e:
            fd.close()
            os.remove(fp)
            raise e
        fd.close()
        jfps = []
        zfd = zipfile.ZipFile(fp, 'r')
        try:
            for jfn in jfns:
                jfp = os.path.join(FOLDER, jfn)
                if not os.path.exists(jfp):
                    jfps.append(jfp)
                    jentry = '%s/lib/%s' % (os.path.basename(GRID_URL)[:-8], jfn)
                    jfd = open(jfp, 'wb')
                    jfd.write(zfd.read(jentry))
                    jfd.close()
        except Exception, e:
            zfd.close()
            os.remove(fp)
            for jfp in jfps:
                os.remove(jfp)
            raise e
        zfd.close()
        os.remove(fp)
    
    